import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useAIChatStore } from '@/stores/aiChatStore'
import type {
  WorkRecord,
  WorkCategory,
  CreateWorkRecordRequest,
  UpdateWorkRecordRequest,
  GenerateReportRequest,
  GeneratedReportResponse,
  WorkRecordQueryParams,
  PageResponse,
  GeneratedReport,
  ReportQueryRequest,
  ReportUpdateRequest,
  BatchOperationRequest,
  ReportStats,
  ReportFilters,
  PaginationInfo
} from '@/types/workReport'
import * as workReportApi from '@/api/workReport'
import { ElMessage } from 'element-plus'

export const useWorkReportStore = defineStore('workReport', () => {
  // ==================== 状态 ====================
  
  // 工作记录
  const records = ref<WorkRecord[]>([])
  const currentRecord = ref<WorkRecord | null>(null)
  const recordsLoading = ref(false)
  const recordsPagination = ref({
    page: 0,
    size: 20,
    total: 0,
    totalPages: 0
  })

  // 工作分类
  const categories = ref<WorkCategory[]>([])
  const categoriesLoading = ref(false)

  // 报告生成
  const generatedReport = ref<GeneratedReportResponse | null>(null)
  const reportGenerating = ref(false)

  // 报告管理
  const reports = ref<GeneratedReport[]>([])
  const currentReport = ref<GeneratedReport | null>(null)
  const reportsLoading = ref(false)
  const reportFilters = ref<ReportFilters>({})
  const reportPagination = ref<PaginationInfo>({
    page: 0,
    size: 10,
    total: 0,
    totalPages: 0
  })
  const reportStats = ref<ReportStats | null>(null)
  const statsLoading = ref(false)

  // 分类统计数据
  const categoryStats = ref<Record<string, number>>({})
  const categoryStatsLoading = ref(false)

  // 查询参数
  const queryParams = ref<WorkRecordQueryParams>({
    page: 0,
    size: 20
  })

  // ==================== 计算属性 ====================
  
  const userCategories = computed(() => 
    categories.value.filter(cat => !cat.isSystem)
  )

  const systemCategories = computed(() => 
    categories.value.filter(cat => cat.isSystem)
  )

  const todayRecords = computed(() => {
    const today = new Date().toISOString().split('T')[0]
    return records.value.filter(record => record.date === today)
  })

  const completedRecordsCount = computed(() => 
    records.value.filter(record => record.status === 'COMPLETED').length
  )

  const totalTimeSpent = computed(() => 
    records.value.reduce((total, record) => total + (record.timeSpent || 0), 0)
  )

  // ==================== 工作分类操作 ====================

  /**
   * 获取用户分类
   */
  const fetchCategories = async () => {
    try {
      categoriesLoading.value = true
      const response = await workReportApi.getUserCategories()
      // 修复：从ApiResponse中提取data字段，确保categories是数组
      categories.value = response.data || []
    } catch (error) {
      console.error('获取分类失败:', error)
      ElMessage.error('获取分类失败')
      // 确保出错时categories仍然是数组
      categories.value = []
    } finally {
      categoriesLoading.value = false
    }
  }

  /**
   * 创建分类
   */
  const createCategory = async (categoryData: {
    name: string
    description?: string
    color?: string
    icon?: string
  }) => {
    try {
      const response = await workReportApi.createCategory(categoryData)
      // 修复：从ApiResponse中提取data字段
      const newCategory = response.data || response
      categories.value.push(newCategory)
      ElMessage.success('分类创建成功')
      return newCategory
    } catch (error) {
      console.error('创建分类失败:', error)
      ElMessage.error('创建分类失败')
      throw error
    }
  }

  /**
   * 更新分类
   */
  const updateCategory = async (categoryId: number, categoryData: {
    name?: string
    description?: string
    color?: string
    icon?: string
  }) => {
    try {
      const response = await workReportApi.updateCategory(categoryId, categoryData)
      // 修复：从ApiResponse中提取data字段
      const updatedCategory = response.data || response
      const index = categories.value.findIndex(cat => cat.id === categoryId)
      if (index !== -1) {
        categories.value[index] = updatedCategory
      }
      ElMessage.success('分类更新成功')
      return updatedCategory
    } catch (error) {
      console.error('更新分类失败:', error)
      ElMessage.error('更新分类失败')
      throw error
    }
  }

  /**
   * 删除分类
   */
  const deleteCategory = async (categoryId: number) => {
    try {
      await workReportApi.deleteCategory(categoryId)
      categories.value = categories.value.filter(cat => cat.id !== categoryId)
      ElMessage.success('分类删除成功')
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error('删除分类失败')
      throw error
    }
  }

  // ==================== 辅助函数 ====================

  /**
   * 解析标签JSON字符串
   */
  const parseTags = (tags: any): string[] => {
    if (!tags) return []

    // 如果已经是数组，直接返回
    if (Array.isArray(tags)) return tags

    // 如果是字符串，尝试解析JSON
    if (typeof tags === 'string') {
      try {
        let parsed = JSON.parse(tags)

        // 处理嵌套JSON的情况
        while (typeof parsed === 'string') {
          parsed = JSON.parse(parsed)
        }

        return Array.isArray(parsed) ? parsed : []
      } catch (error) {
        console.warn('解析标签失败:', tags, error)
        return []
      }
    }

    return []
  }

  // ==================== 工作记录操作 ====================

  /**
   * 获取工作记录列表
   */
  const fetchRecords = async (params?: WorkRecordQueryParams) => {
    try {
      recordsLoading.value = true
      const queryData = { ...queryParams.value, ...params }
      const response = await workReportApi.getUserWorkRecords(queryData)

      // {{ AURA-X: Modify - 修复数据访问路径，从response.content改为response.data.content. Approval: 寸止(ID:fix-data-access). }}
      const content = response.data?.content || []
      // 解析标签JSON字符串
      records.value = content.map(record => ({
        ...record,
        tags: parseTags(record.tags)
      }))
      recordsPagination.value = {
        page: response.data?.number || 0,
        size: response.data?.size || 10,
        total: response.data?.totalElements || 0,
        totalPages: response.data?.totalPages || 0
      }
    } catch (error) {
      console.error('获取工作记录失败:', error)
      ElMessage.error('获取工作记录失败')
    } finally {
      recordsLoading.value = false
    }
  }

  /**
   * 根据日期获取工作记录
   */
  const fetchRecordsByDate = async (date: string) => {
    try {
      recordsLoading.value = true
      const response = await workReportApi.getWorkRecordsByDate(date)
      // {{ AURA-X: Modify - 修复数据访问路径，确保正确获取数据. Approval: 寸止(ID:fix-data-access). }}
      const data = response.data || response
      records.value = (Array.isArray(data) ? data : []).map(record => ({
        ...record,
        tags: parseTags(record.tags)
      }))
    } catch (error) {
      console.error('获取工作记录失败:', error)
      ElMessage.error('获取工作记录失败')
    } finally {
      recordsLoading.value = false
    }
  }

  /**
   * 创建工作记录
   */
  const createRecord = async (recordData: CreateWorkRecordRequest) => {
    try {
      const newRecord = await workReportApi.createWorkRecord(recordData)
      // 解析标签
      const recordWithParsedTags = {
        ...newRecord,
        tags: parseTags(newRecord.tags)
      }
      records.value.unshift(recordWithParsedTags)
      ElMessage.success('工作记录创建成功')
      return recordWithParsedTags
    } catch (error) {
      console.error('创建工作记录失败:', error)
      ElMessage.error('创建工作记录失败')
      throw error
    }
  }

  /**
   * 更新工作记录
   */
  const updateRecord = async (recordId: number, recordData: UpdateWorkRecordRequest) => {
    try {
      const updatedRecord = await workReportApi.updateWorkRecord(recordId, recordData)
      // 解析标签
      const recordWithParsedTags = {
        ...updatedRecord,
        tags: parseTags(updatedRecord.tags)
      }
      const index = records.value.findIndex(record => record.id === recordId)
      if (index !== -1) {
        records.value[index] = recordWithParsedTags
      }
      if (currentRecord.value?.id === recordId) {
        currentRecord.value = recordWithParsedTags
      }
      ElMessage.success('工作记录更新成功')
      return updatedRecord
    } catch (error) {
      console.error('更新工作记录失败:', error)
      ElMessage.error('更新工作记录失败')
      throw error
    }
  }

  /**
   * 删除工作记录
   */
  const deleteRecord = async (recordId: number) => {
    try {
      await workReportApi.deleteWorkRecord(recordId)
      records.value = records.value.filter(record => record.id !== recordId)
      if (currentRecord.value?.id === recordId) {
        currentRecord.value = null
      }
      ElMessage.success('工作记录删除成功')
    } catch (error) {
      console.error('删除工作记录失败:', error)
      ElMessage.error('删除工作记录失败')
      throw error
    }
  }

  /**
   * 设置当前记录
   */
  const setCurrentRecord = (record: WorkRecord | null) => {
    currentRecord.value = record
  }

  // ==================== 工具函数 ====================

  /**
   * 获取工作报告设置
   */
  const getWorkReportSettings = () => {
    try {
      const aiChatStore = useAIChatStore()
      const savedSettings = localStorage.getItem('workReportSettings')

      if (savedSettings) {
        const settings = JSON.parse(savedSettings)
        return {
          model: aiChatStore.currentModel, // 使用全局AI模型设置
          temperature: settings.aiSettings?.temperature || 0.7,
          maxLength: settings.aiSettings?.maxLength || 2000,
          style: settings.aiSettings?.style || 'professional',
          includeContent: settings.aiSettings?.includeContent || ['summary', 'achievements', 'nextSteps']
        }
      }

      // 默认设置
      return {
        model: aiChatStore.currentModel,
        temperature: 0.7,
        maxLength: 2000,
        style: 'professional',
        includeContent: ['summary', 'achievements', 'nextSteps']
      }
    } catch (error) {
      console.error('获取工作报告设置失败:', error)
      // 返回默认设置
      const aiChatStore = useAIChatStore()
      return {
        model: aiChatStore.currentModel,
        temperature: 0.7,
        maxLength: 2000,
        style: 'professional',
        includeContent: ['summary', 'achievements', 'nextSteps']
      }
    }
  }

  // ==================== 报告生成操作 ====================

  /**
   * 生成报告
   */
  const generateReport = async (reportData: GenerateReportRequest) => {
    try {
      reportGenerating.value = true

      // 获取工作报告设置并合并到请求数据中
      const settings = getWorkReportSettings()
      const requestData = {
        ...reportData,
        ...settings
      }

      const response = await workReportApi.generateReport(requestData)
      // 修复：从ApiResponse中提取data字段，确保generatedReport有正确的数据结构
      generatedReport.value = response.data || response
      ElMessage.success('报告生成成功')
      return generatedReport.value
    } catch (error: any) {
      console.error('生成报告失败:', error)

      // 处理业务异常 - 显示具体的错误信息
      if (error.response?.data?.message) {
        // 后端返回的业务异常信息
        ElMessage.error(error.response.data.message)
      } else if (error.message) {
        // 其他错误信息
        ElMessage.error(error.message)
      } else if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
        ElMessage.error('AI服务响应超时，请稍后重试。如果问题持续存在，请检查网络连接。')
      } else {
        // 默认错误信息
        ElMessage.error('生成报告失败，请稍后重试')
      }

      throw error
    } finally {
      reportGenerating.value = false
    }
  }

  /**
   * 快速生成今日日报
   */
  const generateTodayReport = async () => {
    try {
      reportGenerating.value = true

      // 获取工作报告设置
      const settings = getWorkReportSettings()

      const response = await workReportApi.generateTodayReport(settings)
      // 修复：从ApiResponse中提取data字段，确保generatedReport有正确的数据结构
      generatedReport.value = response.data || response
      ElMessage.success('今日日报生成成功')
      return generatedReport.value
    } catch (error: any) {
      console.error('生成今日日报失败:', error)

      // 处理业务异常 - 显示具体的错误信息
      if (error.response?.data?.message) {
        // 后端返回的业务异常信息
        ElMessage.error(error.response.data.message)
      } else if (error.message) {
        // 其他错误信息
        ElMessage.error(error.message)
      } else if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
        ElMessage.error('AI服务响应超时，请稍后重试。如果问题持续存在，请检查网络连接。')
      } else {
        // 默认错误信息
        ElMessage.error('生成今日日报失败，请稍后重试')
      }

      throw error
    } finally {
      reportGenerating.value = false
    }
  }

  /**
   * 清除生成的报告
   */
  const clearGeneratedReport = () => {
    generatedReport.value = null
  }

  /**
   * 保存报告到历史记录
   */
  const saveReportToHistory = async (saveData: any) => {
    try {
      const reportId = await workReportApi.saveReportToHistory(saveData)
      return reportId
    } catch (error: any) {
      console.error('保存报告失败:', error)
      throw error
    }
  }

  // ==================== 报告管理 ====================

  /**
   * 获取报告列表
   */
  const fetchReports = async (queryRequest?: ReportQueryRequest) => {
    try {
      reportsLoading.value = true

      const params = {
        page: queryRequest?.page ?? reportPagination.value.page,
        size: queryRequest?.size ?? reportPagination.value.size,
        type: queryRequest?.type ?? reportFilters.value.type,
        status: queryRequest?.status ?? reportFilters.value.status,
        keyword: queryRequest?.keyword ?? reportFilters.value.keyword,
        startDate: queryRequest?.startDate ?? reportFilters.value.startDate,
        endDate: queryRequest?.endDate ?? reportFilters.value.endDate,
        sortBy: queryRequest?.sortBy ?? 'createdAt',
        sortDirection: queryRequest?.sortDirection ?? 'DESC'
      }

      const response = await workReportApi.getReportList(params)

      // {{ AURA-X: Modify - 修复数据访问路径，从response.content改为response.data.content. Approval: 寸止(ID:fix-data-access). }}
      reports.value = response.data?.content || []
      reportPagination.value = {
        page: response.data?.number || 0,
        size: response.data?.size || 10,
        total: response.data?.totalElements || 0,
        totalPages: response.data?.totalPages || 0
      }

      // 更新筛选条件
      if (queryRequest) {
        reportFilters.value = {
          type: queryRequest.type,
          status: queryRequest.status,
          keyword: queryRequest.keyword,
          startDate: queryRequest.startDate,
          endDate: queryRequest.endDate
        }
      }

    } catch (error: any) {
      console.error('获取报告列表失败:', error)
      ElMessage.error(error.message || '获取报告列表失败')
    } finally {
      reportsLoading.value = false
    }
  }

  /**
   * 获取报告详情
   */
  const fetchReportDetail = async (reportId: number) => {
    try {
      const response = await workReportApi.getReportDetail(reportId)
      // 修复：从ApiResponse中提取data字段
      currentReport.value = response.data || response
      return currentReport.value
    } catch (error: any) {
      console.error('获取报告详情失败:', error)
      ElMessage.error(error.message || '获取报告详情失败')
      throw error
    }
  }

  /**
   * 更新报告
   */
  const updateReport = async (reportId: number, updateRequest: ReportUpdateRequest) => {
    try {
      const updatedReport = await workReportApi.updateReport(reportId, updateRequest)

      // 更新列表中的报告
      const index = reports.value.findIndex(r => r.id === reportId)
      if (index !== -1) {
        reports.value[index] = updatedReport
      }

      // 更新当前报告
      if (currentReport.value?.id === reportId) {
        currentReport.value = updatedReport
      }

      ElMessage.success('报告更新成功')
      return updatedReport
    } catch (error: any) {
      console.error('更新报告失败:', error)
      ElMessage.error(error.message || '更新报告失败')
      throw error
    }
  }

  /**
   * 删除报告
   */
  const deleteReport = async (reportId: number) => {
    try {
      await workReportApi.deleteReport(reportId)

      // 从列表中移除
      reports.value = reports.value.filter(r => r.id !== reportId)

      // 清除当前报告
      if (currentReport.value?.id === reportId) {
        currentReport.value = null
      }

      // 更新分页信息
      reportPagination.value.total = Math.max(0, reportPagination.value.total - 1)

      ElMessage.success('报告删除成功')
    } catch (error: any) {
      console.error('删除报告失败:', error)
      ElMessage.error(error.message || '删除报告失败')
      throw error
    }
  }

  /**
   * 批量删除报告
   */
  const batchDeleteReports = async (reportIds: number[]) => {
    try {
      await workReportApi.batchDeleteReports({ reportIds, operation: 'DELETE' })

      // 从列表中移除
      reports.value = reports.value.filter(r => !reportIds.includes(r.id))

      // 清除当前报告
      if (currentReport.value && reportIds.includes(currentReport.value.id)) {
        currentReport.value = null
      }

      // 更新分页信息
      reportPagination.value.total = Math.max(0, reportPagination.value.total - reportIds.length)

      ElMessage.success(`成功删除 ${reportIds.length} 个报告`)
    } catch (error: any) {
      console.error('批量删除报告失败:', error)
      ElMessage.error(error.message || '批量删除报告失败')
      throw error
    }
  }

  /**
   * 获取报告统计
   */
  const fetchReportStats = async () => {
    try {
      statsLoading.value = true
      const response = await workReportApi.getReportStats()
      // {{ AURA-X: Modify - 修复统计数据访问路径，从response改为response.data. Approval: 寸止(ID:fix-stats-access). }}
      const stats = response.data || response
      reportStats.value = stats
      return stats
    } catch (error: any) {
      console.error('获取报告统计失败:', error)
      ElMessage.error(error.message || '获取报告统计失败')
      throw error
    } finally {
      statsLoading.value = false
    }
  }

  /**
   * 获取分类统计
   */
  const fetchCategoryStats = async () => {
    try {
      categoryStatsLoading.value = true
      const response = await workReportApi.getCategoryStats()
      // 从ApiResponse中提取data字段
      const stats = response.data || response
      categoryStats.value = stats
      return stats
    } catch (error: any) {
      console.error('获取分类统计失败:', error)
      ElMessage.error(error.message || '获取分类统计失败')
      throw error
    } finally {
      categoryStatsLoading.value = false
    }
  }

  /**
   * 导出报告
   */
  const exportReport = async (reportId: number, format: 'PDF' | 'WORD' | 'MARKDOWN', includeOriginal = false) => {
    try {
      const content = await workReportApi.exportReport(reportId, format, includeOriginal)

      // 创建下载链接
      const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url

      // 获取报告信息用于文件名
      const report = reports.value.find(r => r.id === reportId) || currentReport.value
      const fileName = report ? `${report.title}.${format.toLowerCase()}` : `report_${reportId}.${format.toLowerCase()}`

      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      ElMessage.success('报告导出成功')
    } catch (error: any) {
      console.error('导出报告失败:', error)
      ElMessage.error(error.message || '导出报告失败')
      throw error
    }
  }

  /**
   * 设置当前报告
   */
  const setCurrentReport = (report: GeneratedReport | null) => {
    currentReport.value = report
  }

  /**
   * 清除报告管理状态
   */
  const clearReportManageState = () => {
    reports.value = []
    currentReport.value = null
    reportFilters.value = {}
    reportPagination.value = {
      page: 0,
      size: 10,
      total: 0,
      totalPages: 0
    }
    reportStats.value = null
  }

  // ==================== 工具方法 ====================

  /**
   * 重置状态
   */
  const reset = () => {
    records.value = []
    currentRecord.value = null
    categories.value = []
    generatedReport.value = null
    recordsLoading.value = false
    categoriesLoading.value = false
    reportGenerating.value = false
    recordsPagination.value = {
      page: 0,
      size: 20,
      total: 0,
      totalPages: 0
    }
    queryParams.value = {
      page: 0,
      size: 20
    }

    // 重置报告管理状态
    clearReportManageState()
    reportsLoading.value = false
    statsLoading.value = false
  }

  return {
    // 状态
    records,
    currentRecord,
    recordsLoading,
    recordsPagination,
    categories,
    categoriesLoading,
    generatedReport,
    reportGenerating,
    queryParams,

    // 报告管理状态
    reports,
    currentReport,
    reportsLoading,
    reportFilters,
    reportPagination,
    reportStats,
    statsLoading,
    categoryStats,
    categoryStatsLoading,

    // 计算属性
    userCategories,
    systemCategories,
    todayRecords,
    completedRecordsCount,
    totalTimeSpent,

    // 分类操作
    fetchCategories,
    createCategory,
    updateCategory,
    deleteCategory,

    // 记录操作
    fetchRecords,
    fetchRecordsByDate,
    createRecord,
    updateRecord,
    deleteRecord,
    setCurrentRecord,

    // 报告生成
    generateReport,
    generateTodayReport,
    clearGeneratedReport,
    saveReportToHistory,

    // 报告管理
    fetchReports,
    fetchReportDetail,
    updateReport,
    deleteReport,
    batchDeleteReports,
    fetchReportStats,
    fetchCategoryStats,
    exportReport,
    setCurrentReport,
    clearReportManageState,

    // 工具方法
    reset
  }
})
